//
//  HomePageViewController.m
//  MagicFang
//
//  Created by 华谕 on 2017/11/30.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "HomePageViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <MAMapKit/MAAnnotation.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "CustomAnnotationView.h"
#import "LocationModel.h"
#import "LeftMenuViewController.h"
#import "AboutUsViewController.h"
#import "PersonDataViewController.h"
#import "SetUpViewController.h"
#import "ChosseCityViewController.h"
#import "HYNavBaseViewController.h"
#import "FactoryDetailsViewController.h"
#import "SystemMessageViewController.h"
#import "LoginOrRegisterViewController.h"
#import "UserModel.h"

#define kCalloutViewMargin          -8
@interface HomePageViewController ()<MAMapViewDelegate,LeftMenuControllerDelegate, CLLocationManagerDelegate>
{
    UIImageView *signImageView;
}
@property (nonatomic,strong) LeftMenuViewController *menu;
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) NSArray *locaAry;
@property (nonatomic, strong) UIButton *titleBtn;
@property (nonatomic, copy) NSString *cityName;
@property (nonatomic, strong) CLLocationManager *locationManager;
@end

@implementation HomePageViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [AMapServices sharedServices].apiKey = GAODEKEY;
    [self locate];
    [self creatUI];
    NSDictionary *dic = @{@"lng":@"114.229250000000",
                          @"lat":@"22.684500000000"
                          };
    [self requestContractorMap:dic];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"test" object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestGetUserInfo];
    [self requestMessageIsRead];
}

- (void)test {
    [self requestMessageIsRead];
}

- (void)creatUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    UIImage *leftBtnImage = [[UIImage imageNamed:@"geren"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:leftBtnImage style:UIBarButtonItemStyleDone target:self action:@selector(openLeftView)];
//    UIImage *rightBtnImage = [[UIImage imageNamed:@"xiaoxi"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:rightBtnImage style:UIBarButtonItemStyleDone target:self action:@selector(messageAction)];
    UIButton *rightBtn = [ZCControl createButtonWithFrame:CGRectMake(0, 0, 20, 20) ImageName:@"xiaoxi" Target:self Action:@selector(messageAction) Title:nil Font:10];
    UIBarButtonItem *rightBarBtnItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem.customView = rightBtn;
    
    signImageView = [ZCControl createImageViewWithFrame:CGRectMake(15, -2, 8, 8) ImageName:nil];
    signImageView.layer.cornerRadius = 4;
    signImageView.layer.masksToBounds = YES;
    signImageView.backgroundColor = [UIColor redColor];
    signImageView.hidden = YES;
    [rightBtn addSubview:signImageView];
    self.navigationItem.rightBarButtonItem = rightBarBtnItem;
    
    ///地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
    [AMapServices sharedServices].enableHTTPS = YES;
    
    ///初始化地图
   self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _mapView.delegate = self;
    ///把地图添加至view
    [self.view addSubview:_mapView];
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    UIButton *loginBtn = [ZCControl createButtonWithFrame:CGRectMake(20*displaywidth ,SCREEN_HEIGHT-50*displaywidth-STA_NAV_HEIGHT, 40*displaywidth, 40*displaywidth) ImageName:@"dingwei111" Target:self Action:@selector(loginBtnBtnAction) Title:nil Font:15.0];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginBtn.backgroundColor = [UIColor clearColor];
    [loginBtn.layer setMasksToBounds:YES];
    [loginBtn.layer setCornerRadius:5*displaywidth];
    [self.view addSubview:loginBtn];
    // 添加一个定点的图片（视图中心）
    UIImageView *locaImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2, (SCREEN_HEIGHT - STA_NAV_HEIGHT - SCREER_HeiX) / 2 + 14, 25, 24)];
    locaImageView.image = [UIImage imageNamed:@"dibiao"];
    locaImageView.center = CGPointMake(_mapView.center.x, (SCREEN_HEIGHT - STA_NAV_HEIGHT - SCREER_HeiX) / 2);
    [self.view addSubview:locaImageView];
    
}

#pragma mark 定位

- (void)locate

{
    if (!self.locationManager)
    {
        
        self.locationManager = [[CLLocationManager alloc] init];
        
        self.locationManager.delegate = self;
        self.locationManager.distanceFilter=1.0;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
        {
            [self.locationManager requestWhenInUseAuthorization];
        }
        [self.locationManager startUpdatingLocation];
        
    } else {
        [self.locationManager startUpdatingLocation];
    }
    
}
#pragma mark - CoreLocation Delegate 实现定位协议回调方法

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

{
    
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    
    CLLocation *currentLocation = [locations lastObject];
    
    // 获取当前所在的城市名
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    //根据经纬度反向地理编译出地址信息
    
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     
     {
         
         if (array.count > 0)
             
         {
             
             CLPlacemark *placemark = [array objectAtIndex:0];
             //获取城市
             
             NSString *city = placemark.locality;
             
             if (!city) {
                 
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 city = placemark.administrativeArea;
                 
             }
             self.titleBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 150, 44)];
             _titleBtn.backgroundColor = [UIColor clearColor];
             _titleBtn.titleLabel.font = [UIFont systemFontOfSize:15];
             [_titleBtn addTarget:self action:@selector(changeCity) forControlEvents:UIControlEventTouchUpInside];
             [_titleBtn setImage:[UIImage imageNamed:@"chengshixuanz-"] forState:UIControlStateNormal];
             [_titleBtn setTitle:city forState:UIControlStateNormal];
             CGSize titleSize = [_titleBtn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:_titleBtn.titleLabel.font}];
             CGSize imgSize = _titleBtn.currentImage.size;
             UIEdgeInsets   titleEdgeInsets = UIEdgeInsetsMake(0, -imgSize.width-5, 0, imgSize.width+5);
             UIEdgeInsets imgEdgeInsets = UIEdgeInsetsMake(0, 5+titleSize.width, 0, -titleSize.width-5);
             _titleBtn.titleEdgeInsets = titleEdgeInsets;
             _titleBtn.imageEdgeInsets = imgEdgeInsets;
             self.navigationItem.titleView = _titleBtn;
             
             [manager stopUpdatingLocation];
         }
         
         else if (error == nil && [array count] == 0)
             
         {
             self.cityName=@"定位失败";
         }
         
         else if (error != nil)
             
         {
             self.cityName=@"定位失败";
             
         }
         
     }];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    
    if (error.code == kCLErrorDenied) {
        self.cityName=@"定位失败";
        
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
    }
}

- (void)requestMessageIsRead {
    WEAKSELF;
    //    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestMessageIsReadParmers:nil Success:^(id obj)
     {
         //         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([obj server_Getcodecheck])
         {
             NSLog(@"%@", obj);
             NSInteger num = [obj[@"data"] integerValue];
             if (num>0) {
                 signImageView.hidden = NO;
             } else {
                 signImageView.hidden = YES;
             }
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         //         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
     }];
}

- (void)changeCity {
    if (![LTools storageForKey:SERVER_IsLogin])
    {
        LoginOrRegisterViewController *vc = [[LoginOrRegisterViewController alloc] init];
        HYNavBaseViewController *nav = [[HYNavBaseViewController alloc] initWithRootViewController:vc];
        [self presentViewController:nav animated:YES completion:nil];
        return;
    }
    ChosseCityViewController *chosseCityVC = [[ChosseCityViewController alloc] init];
    chosseCityVC.cityBlockWithName = ^(NSString *cityName, CLLocationCoordinate2D coordinate) {
        [_titleBtn setTitle:cityName forState:UIControlStateNormal];
        CGSize titleSize = [_titleBtn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:_titleBtn.titleLabel.font}];
        CGSize imgSize = _titleBtn.currentImage.size;
        UIEdgeInsets titleEdgeInsets = UIEdgeInsetsMake(0, -imgSize.width-5, 0, imgSize.width+5);
        UIEdgeInsets imgEdgeInsets = UIEdgeInsetsMake(0, 5+titleSize.width, 0, -titleSize.width-5);
        _titleBtn.titleEdgeInsets = titleEdgeInsets;
        _titleBtn.imageEdgeInsets = imgEdgeInsets;
        _mapView.centerCoordinate = coordinate;
//        CLGeocoder *geocode = [[CLGeocoder alloc] init];
//        [geocode geocodeAddressString:cityName completionHandler:^(NSArray *placemarks, NSError *error) {
//            CLPlacemark * placemark = placemarks[0];
//            _mapView.centerCoordinate = placemark.location.coordinate;
//        }];
    };
    chosseCityVC.currentCityName = _titleBtn.titleLabel.text;
    [self.navigationController pushViewController:chosseCityVC animated:YES];
}

//个人中心
- (void)openLeftView
{
    if (!self.menu) {
        self.menu = [[LeftMenuViewController alloc] init];
        _menu.clectedDelected = self;
        CGRect frame = self.menu.view.frame;
        frame.origin.x = - CGRectGetWidth(self.view.frame);
        self.menu.view.frame = frame;
        
        [[UIApplication sharedApplication].keyWindow addSubview:self.menu.view];
    }
    [self.menu showFromLeft];
}

- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction
{
    NSDictionary *dic = @{@"lng":s_float(_mapView.centerCoordinate.longitude),
                          @"lat":s_float(_mapView.centerCoordinate.latitude)
                          };
    dispatch_async(dispatch_get_main_queue(), ^{
        NSArray *laseAry = [_locaAry copy];
        if (laseAry.count > 0)
        {
            [_mapView removeOverlays:_mapView.overlays];
            [_mapView removeAnnotations:_mapView.annotations];
        }
        [self requestContractorMap:dic];
    });
   
}

//消息
- (void)messageAction
{
    if (![LTools storageForKey:SERVER_IsLogin])
    {
        LoginOrRegisterViewController *vc = [[LoginOrRegisterViewController alloc] init];
        HYNavBaseViewController *nav = [[HYNavBaseViewController alloc] initWithRootViewController:vc];
        [self presentViewController:nav animated:YES completion:nil];
        return;
    }
    SystemMessageViewController *vc = [[SystemMessageViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)selectedValue:(NSInteger)index andInterger:(NSInteger)num
{
    NSArray *classArray = @[@"LoginOrRegisterViewController", @"PersonDataViewController", @"MyWalletViewController", @"CollectViewController",@"MyJobsViewController",@"ProjectManagementViewController",@"AttendanceQueryViewController",@"FeedBackViewController",@""];
    if (num==7)
    {
        classArray = @[@"LoginOrRegisterViewController", @"PersonDataViewController", @"MyWalletViewController", @"CollectViewController",@"MyJobsViewController",@"AttendanceQueryViewController",@"FeedBackViewController",@""];
    }
    
    if (![LTools storageForKey:SERVER_IsLogin])
    {
        HYBaseViewController *vc = [[NSClassFromString(classArray[0]) alloc] init];
        HYNavBaseViewController *nav = [[HYNavBaseViewController alloc] initWithRootViewController:vc];
        [self presentViewController:nav animated:YES completion:nil];
        return;
    }
    HYBaseViewController *VC = [[NSClassFromString(classArray[index]) alloc] init];
    [self.navigationController pushViewController:VC animated:YES];
}

- (void)clickTypeValue:(NSInteger)index
{
    NSArray *classArray = @[@"LoginOrRegisterViewController", @"RealNameViewController", @"SetUpViewController", @"AboutUsViewController",@"",@""];
    
    HYBaseViewController *VC = [[NSClassFromString(classArray[index]) alloc] init];
    if (index == 0)
    {
        HYNavBaseViewController *nav = [[HYNavBaseViewController alloc] initWithRootViewController:VC];
        [self presentViewController:nav animated:YES completion:nil];

    }
    else
    {
        if (![LTools storageForKey:SERVER_IsLogin])
        {
            HYBaseViewController *vc = [[NSClassFromString(classArray[0]) alloc] init];
            HYNavBaseViewController *nav = [[HYNavBaseViewController alloc] initWithRootViewController:vc];
            [self presentViewController:nav animated:YES completion:nil];
            return;
        }
        [self.navigationController pushViewController:VC animated:YES];

    }
}


- (void)loginBtnBtnAction
{
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
}






#pragma mark - Utility

-(void)addAnnotationWithCooordinate:(NSArray *)coorAry
{
    NSMutableArray *CooordinateAry = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < coorAry.count; i++)
    {
        LocationModel *model = coorAry[i];
        CLLocationCoordinate2D coords = CLLocationCoordinate2DMake([model.lat floatValue], [model.lng floatValue]);
        MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
        annotation.coordinate = coords;
        annotation.title    = [NSString stringWithFormat:@"%d",i];
        annotation.subtitle = [NSString stringWithFormat:@"%@,%@",model.headImg,model.name];
        [CooordinateAry addObject:annotation];
    }
    [self.mapView addAnnotations:CooordinateAry];
}

- (void)removeAnnotationWithCooordinate:(NSArray *)coorAry
{
    NSMutableArray *CooordinateAry = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < coorAry.count; i++)
    {
        LocationModel *model = coorAry[i];
        CLLocationCoordinate2D coords = CLLocationCoordinate2DMake([model.lat floatValue], [model.lng floatValue]);
        MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
        annotation.coordinate = coords;
        annotation.title    = [NSString stringWithFormat:@"%d",i];
        annotation.subtitle = [NSString stringWithFormat:@"%@,%@",model.headImg,model.name];
        [CooordinateAry addObject:annotation];
    }
    [self.mapView removeAnnotations:CooordinateAry];
}

- (CGPoint)randomPoint
{
    CGPoint randomPoint = CGPointZero;
    
    randomPoint.x = arc4random() % (int)(CGRectGetWidth(self.view.bounds));
    randomPoint.y = arc4random() % (int)(CGRectGetHeight(self.view.bounds));
    
    return randomPoint;
}

- (CGSize)offsetToContainRect:(CGRect)innerRect inRect:(CGRect)outerRect
{
    CGFloat nudgeRight = fmaxf(0, CGRectGetMinX(outerRect) - (CGRectGetMinX(innerRect)));
    CGFloat nudgeLeft = fminf(0, CGRectGetMaxX(outerRect) - (CGRectGetMaxX(innerRect)));
    CGFloat nudgeTop = fmaxf(0, CGRectGetMinY(outerRect) - (CGRectGetMinY(innerRect)));
    CGFloat nudgeBottom = fminf(0, CGRectGetMaxY(outerRect) - (CGRectGetMaxY(innerRect)));
    return CGSizeMake(nudgeLeft ?: nudgeRight, nudgeTop ?: nudgeBottom);
}

#pragma mark - MAMapViewDelegate

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAUserLocation class]])
    {
        return nil;
    }
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *customReuseIndetifier = @"customReuseIndetifier";
        
        CustomAnnotationView *annotationView = (CustomAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            // must set to NO, so we can show the custom callout view.
            annotationView.canShowCallout = NO;
            annotationView.draggable = YES;
            annotationView.calloutOffset = CGPointMake(0, -5);
        }
        annotationView.portrait = [UIImage imageNamed:@"gongcMap"];
        return annotationView;
    }
    
    return nil;
}



- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
    /* Adjust the map center in order to show the callout view completely. */
    if ([view isKindOfClass:[CustomAnnotationView class]]) {
        CustomAnnotationView *cusView = (CustomAnnotationView *)view;
        
        CGRect frame = [cusView convertRect:cusView.calloutView.frame toView:self.mapView];
        
        frame = UIEdgeInsetsInsetRect(frame, UIEdgeInsetsMake(kCalloutViewMargin, kCalloutViewMargin, kCalloutViewMargin, kCalloutViewMargin));
        WEAKSELF;
        cusView.pushBlock = ^(NSInteger index) {
            if (index < _locaAry.count)
            {
                LocationModel *model = weakSelf.locaAry[index];
                FactoryDetailsViewController *vc = [[FactoryDetailsViewController alloc] init];
                vc.companyID = s_str(model.ID);
                [self.navigationController pushViewController:vc animated:YES];
            }
        };
        if (!CGRectContainsRect(self.mapView.frame, frame))
        {
            /* Calculate the offset to make the callout view show up. */
            CGSize offset = [self offsetToContainRect:frame inRect:self.mapView.frame];
            
            CGPoint theCenter = self.mapView.center;
            theCenter = CGPointMake(theCenter.x - offset.width, theCenter.y - offset.height);
            
            CLLocationCoordinate2D coordinate = [self.mapView convertPoint:theCenter toCoordinateFromView:self.mapView];
            
            [self.mapView setCenterCoordinate:coordinate animated:YES];
        }
        
    }
}

- (void)requestContractorMap:(NSDictionary *)dic
{
    WEAKSELF;
    [HYBaseHandler requestContractorMapParmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            NSArray *allLocaArray = [LocationModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self addAnnotationWithCooordinate:allLocaArray];
                weakSelf.locaAry = allLocaArray;
            });
           
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

//个人资料
- (void)requestGetUserInfo
{
    WEAKSELF;
    [HYBaseHandler requestGetUserInfoParmers:nil Success:^(id obj)
     {
         if ([obj server_Getcodecheck])
         {
             UserModel *userModel = [UserModel mj_objectWithKeyValues:obj[@"data"]];
             [LTools cache:userModel.identityId ForKey:@"IdentityId"];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         
     }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
